package com.enjoyor.soa.traffic.util.base;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import com.enjoyor.soa.traffic.util.helper.GeomtryHelper;
import com.enjoyor.soa.traffic.util.helper.LoggerHelper;
import com.enjoyor.soa.traffic.util.helper.TimeHelper;

/**
 * 
 * @ClassName: BaseDataFormat 
 * @Description: TODO(基础类型转换类) 
 * @author xujianjun
 * @email xujianjun@enjoyor.net（根据自身情况修改）
 * @date 2016年9月21日 上午9:36:45
 */
public class BaseDataFormat {

	/**
	 * 
	* @Title: toNum 
	* @Description: TODO(字符串转化为整形数字) 
	* @param num 字符串内容
	* @return 捕获异常后返回0
	* @throws
	 */
	protected int toNum(String num) {
		try {
			return Integer.parseInt(num);
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串格式转换整形数字错误！", ex);
			return 0;
		}
	}

	/**
	 * 
	* @Title: toFloat 
	* @Description: TODO(字符串转化为浮点型数据) 
	* @param str 字符串内容
	* @return 捕获异常后返回0
	* @throws
	 */
	protected float toFloat(String str) {
		try {
			return Float.parseFloat(str);
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串格式转换数字错误！", ex);
			return (float) 0;
		}
	}

	/**
	 * 
	* @Title: toDouble 
	* @Description: TODO(字符串转化为double型数据) 
	* @param str 字符串内容
	* @return 捕获异常后返回0.0
	* @throws
	 */
	protected Double toDouble(String str) {
		try {
			return Double.parseDouble(str);
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串转Double格式错误！", ex);
			return 0.0;
		}
	}

	/**
	 * 
	* @Title: toDate 
	* @Description: TODO(字符串转化为时间格式) 
	* @param str 字符串内容
	* @return 捕获异常后返回当前时间
	* @throws
	 */
	protected Date toDate(String str) {
		try {
			return TimeHelper.StringToDate(str, "yyyy-MM-dd");
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串转时间格式错误！", ex);
			return new Date();
		}
	}
	
	protected Date toDate(String str,String param) {
		try {
			return TimeHelper.StringToDate(str, param);
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串转时间格式错误！", ex);
			return new Date();
		}
	}

	protected String toString(String str) {
		try {
			if (null == str) {
				str = "";
			}
			return str;
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串格式转换错误！", ex);
			return "";
		}
	}
	

    /**
     * 将val转换为类型toType的数据
     * @param val
     * @param toType 支持Integer/int、Long/long、Short/short、Byte/byte、
     * Double/double、Float/float、Boolean/boolean、
     * Date(支持特定format的字符串，如：yyyy-MM-dd HH:mm:ss、yyyy/MM/dd HH:mm:ss、yyyy-MM-dd等)
     * @return 转换失败返回 null
     */
    @SuppressWarnings("unchecked")
	public static <T> T castTo(Object val,Class<T> toType,T defVal){
    	Object ret = null;
    	try{
    		if(val!=null&&!"".equals(val)){
    			try{
    				if(val.getClass().equals(toType)) return (T)val;
				}catch(Throwable e){}
		    	if(toType.equals(String.class)){
		    		ret = val.toString();
				}else if(toType.equals(Integer.class)||toType.equals(int.class)){
					ret = Double.valueOf(val.toString()).intValue();
				}else if(toType.equals(Long.class)||toType.equals(long.class)){
					ret = Double.valueOf(val.toString()).longValue();
				}else if(toType.equals(Short.class)||toType.equals(short.class)){
					ret = Short.parseShort(val.toString());
				}else if(toType.equals(Byte.class)||toType.equals(byte.class)){
					ret = Byte.parseByte(val.toString());
				}else if(toType.equals(Double.class)||toType.equals(double.class)){
					ret = Double.parseDouble(val.toString());
				}else if(toType.equals(Float.class)||toType.equals(float.class)){
					ret = Float.parseFloat(val.toString());
				}else if(toType.equals(Boolean.class)||toType.equals(boolean.class)){
					ret = Boolean.parseBoolean(val.toString());
				}else if(toType.equals(Date.class)){
		    		try{ret = (Date)val;}catch(Throwable e){}
					if(ret==null){
						String strval=val.toString();
						for(String format:SDFS){
							try{
								if(strval.length()==format.length()){
									boolean fit=true;
									for(int i=0;i<format.length();i++){
										if("yMdHmsS".indexOf(format.charAt(i))>=0){
											if(strval.charAt(i)<'0'||strval.charAt(i)>'9'){
												fit=false;break;
											}
										}
									}
									if(fit){
										ret=getSDF(format).parse(strval);
									}
									if(ret==null){
										if(strval.indexOf("T")>=0||strval.indexOf("Z")>=0){
											ret = castTo(strval.replace("T","").replace("Z",""),Date.class);
										}
									}
									if(ret!=null)break;
								}
							}catch(Throwable e){}
						}
						if(ret==null && strval.indexOf("T")>0){
							ret=castTo(strval.replace("T"," ").replace("Z",""),toType);
						}
					}
				}else if(toType.equals(Timestamp.class)){
					if(ret==null) try{ret = (Timestamp)val;}catch(Throwable e){}
					if(ret==null) try{ret = new Timestamp(castTo(val,Date.class).getTime());}catch(Throwable e){}
				}else if(toType.equals(oracle.spatial.geometry.JGeometry.class)){
					ret = GeomtryHelper.getJTring2Geom(val.toString());
				}
    		}
    	}catch(Throwable ex){
			LoggerHelper.LOG.error("字符串转"+toType.getName()+"格式错误！", ex);
		}
		if(ret==null)ret=defVal;
    	return (T) ret;
    }
	public static <T> T castTo(Object val,Class<T> toType){
    	return castTo(val,toType,null);
	}

	static String[] SDFS = new String[]{
			"yyyyMMddHHmmssSSS",
			"yyyyMMddHHmmss",
			"yyyy/MM/dd HH:mm:ss.SSS",
			"yyyy-MM-dd HH:mm:ss.SSS",
			"yyyy-MM-dd HH:mm:ss.S",
			"yyyy-MM-dd HH:mm:ss",
			"yyyy/MM/dd HH:mm:ss",
			"yyyy-MM-dd",
			"yyyy/MM/dd",
			"yyyyMMdd",
			"yyyy年MM月dd日",
			"yyyy年MM月dd日HH点mm分ss秒",
			"yyyy年MM月dd日 HH点mm分ss秒",
			"yyyy年MM月dd日HH时mm分ss秒",
			"yyyy年MM月dd日 HH时mm分ss秒"};
	static Map<String,SimpleDateFormat> mapsdf=new HashMap<String,SimpleDateFormat>();
	static SimpleDateFormat getSDF(String format){
		String key =Thread.currentThread().getId()+"_"+format;
		if(!mapsdf.containsKey(key)){synchronized(mapsdf){if(!mapsdf.containsKey(key)){
			mapsdf.put(key, new SimpleDateFormat(format));
		}}}
		return mapsdf.get(key);
	}

	public static void main(String[] args){
		System.out.println(castTo("2018-06-28T09:34:00.0Z",Date.class));
		System.out.println(castTo("20131213141516",Date.class));
		System.out.println(castTo("20131213141516123",Date.class));
		System.out.println(castTo("2013-12-13",Date.class));
		System.out.println(castTo("2013/12/13",Date.class));
		System.out.println(castTo("2013年12月13日",Date.class));
		System.out.println(castTo("2013-12-13 14:15:16",Date.class));
		System.out.println(castTo("2013/12/13 14:15:16",Date.class));
		System.out.println(castTo("2013-12-13 14:15:16.123",Date.class));
		System.out.println(castTo("2013年12月13日 14时15分16秒",Date.class));
		System.out.println(castTo("2019-02-09T09:21:46Z",Date.class));

		System.out.println(Pattern.matches("[\u4e00-\u9fa5]","浙A".substring(0,1)));

		System.out.println(Pattern.matches("[\u4e00-\u9fa5]","123".substring(0,1)));

		System.out.println(Pattern.matches("[\u4e00-\u9fa5]","AVD".substring(0,1)));

		System.out.println(Pattern.matches("[\u4e00-\u9fa5]","wj".substring(0,1)));

		System.out.println(Pattern.matches("[\u4e00-\u9fa5]","浙A".substring(0,1)));

		System.out.println(Pattern.matches("[\u4e00-\u9fa5]","浙A".substring(0,1)));
	}
}
